/**
 * 
 */
package com.snapp.web.agents;

import java.io.File;
import java.util.HashMap;

import org.apache.log4j.Logger;

import com.snapp.util.object.model.ObjectModel;
import com.snapp.util.templates.Processor;

/**
 * @author Kile
 *
 */
public class ObjectAgent extends SNAppAgent {
	private Logger logger = Logger.getLogger(ObjectAgent.class);
	
	/**
	 * 
	 * @param objGlobalId
	 * @param params
	 * @return
	 */
	public ObjectModel saveObject(String objGlobalId, HashMap<String, Object> params) {
		ObjectModel obj = null;
		// save base object record
		try {
			obj = save("SNAPP_OBJECT", params);
		} catch (Exception e) {
			logger.error("Error saving base object record", e);
		}
		
		// save extension object
		params.put("object", obj.getBean().getPropertyString("id"));
		try {
			save(objGlobalId, params);
		} catch (Exception e) {
			logger.error("Error saving extension object record", e);
		}
		
		// get templates
		String[] templates = ((String) params.get("templates")).split(",");
		if (templates.length > 0) {
			// process the templates
			try {
				Processor proc = obj.getTemplateProcessor(obj);
				for (String t : templates) {
					proc.addTemplate(load("SNAPP_TEMPLATEFILE", "id = "+t));
				}
				// run it
				proc.run(); 
				
				HashMap<String, Object> filep = new HashMap<String, Object>();
				for (File file : proc.getFiles()) {
					// save the physical file
					filep.clear();
					filep.put("id",0);
					filep.put("name",file.getName());
					filep.put("file",file);
					ObjectModel fileob = save("SNAPP_FILE", filep);
					// save the file record
					filep.clear();
					filep.put("id",0);
					filep.put("object", obj.getBean().getPropertyString("id"));
					filep.put("file", fileob.getBean().getPropertyString("id"));
					save("SNAPP_OBJECTFILE", filep);
					
				}
			} catch (Exception e) {
				logger.error("Error running template processor", e);
			}
		}
		return obj;
	}
}
